package main

import (
	"context"
	"log"
	"net"

	mygin "e-commerce/services/inventory-service/api/gin"
	mygrpc "e-commerce/services/inventory-service/api/grpc"
	inventorypb "e-commerce/services/inventory-service/api/pb"
	"e-commerce/services/inventory-service/otel"

	"github.com/gin-gonic/gin"
	"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
	"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
	"google.golang.org/grpc"
)

func main() {
	shutdown, err := otel.InitTracer("inventory-service", "services/inventory-service/config/devconfig.yaml")
	if err != nil {
		log.Fatalf("Failed to initialize tracer: %v", err)
	}
	defer func() {
		if err := shutdown(context.Background()); err != nil {
			log.Printf("Failed to shutdown tracer: %v", err)
		}
	}()
	//gin服务
	inventoryHandler, err := mygin.NewInventoryHandler("services/inventory-service/config/devconfig.yaml")
	if err != nil {
		log.Fatalf("Failed to create inventory handler: %v", err)
	}
	r := gin.Default()
	r.Use(otelgin.Middleware("inventory-service"))
	r.Use(inventoryHandler.Middleware())
	r.POST("/create-stock", inventoryHandler.CreateStock)
	go r.Run(":8084")

	//grpc服务
	inventoryServer := mygrpc.NewInventoryServiceServer("services/inventory-service/config/devconfig.yaml")
	//创建订单队列
	err = inventoryServer.NewOrderQueue()
	if err != nil {
		log.Fatalf("Failed to create order queue: %v", err)
	}
	grpcServer := grpc.NewServer(
		grpc.StatsHandler(otelgrpc.NewServerHandler()),
		grpc.UnaryInterceptor(inventoryServer.AuthMiddleware),
	)
	inventorypb.RegisterInventoryServiceServer(grpcServer, inventoryServer)
	lis, err := net.Listen("tcp", ":50054")
	if err != nil {
		log.Fatalf("Failed to listen: %v", err)
	}
	go grpcServer.Serve(lis)

	//监听rabbitmq队列
	err = inventoryServer.ReservedConsume()
	if err != nil {
		log.Fatalf("Failed to consume reserved messages: %v", err)
	}
	err = inventoryServer.RollbackConsume()
	if err != nil {
		log.Fatalf("Failed to consume rollback messages: %v", err)
	}
	select {}
}
